module.exports = {
    state: {
        accessToken: undefined,
        user: {},
        protectGrant: undefined,
        protectMinutes: 5
    },
    mutations: {
        info (state, data) {
            state.user = {
                name: data.nickname,
                avatar: data.headimgurl,
                desc: data.desc || '这个家伙很懒，什么都没有留下。'
            }
            if(data.uid) {
                state.accessToken = data.uid
                state.user.uid = data.uid
                $store.commit('doRedirect')
            }
        },
        auth (state, form) {
            $store.api.call('user_bind', {message: '绑定账号失败', form}, ({data}) => {
                if(data.token) {
                    state.accessToken = data.token
                    state.user.uid = data.uid
                    $store.commit('doRedirect')
                } else {
                    throw '账号或密码错误'
                }
            })
        },
        unauth (state) {
            $store.api.call('user_unbind', {message: '解绑账号失败'}, () => {
                state.accessToken = undefined
                state.user.uid = undefined
                $router.push('/')
            })
        }
    },
    actions: {
        grant ({commit, state}) {
            state.protectGrant = new Date().getTime() + state.protectMinutes * 60000
            commit('doRedirect')
        },
        loadState ({commit, state}, resolve) {
            $store.api.call('user_menu', {noloading:1, message: '获取用户状态失败'}, ({data}) => {
                commit('menu', data)
                if(resolve && resolve.call) {
                    resolve(data)
                }
            })
        }
    },
    getters: {
        isLogin: (state) => {
            return state.accessToken ? true: false
        },
        userName: (state) => {
            return state.user.name
        },
        userAvatar: (state) => {
            return state.user.avatar ? state.user.avatar : 'assets/img/default/avatar.jpg'
        },
        userDesc: (state) => {
            return state.user.desc
        },
        userID: (state) => {
            return state.user.uid
        },
        grantLimit: (state) => {
            return state.protectGrant
        },
        grantMinuts: (state) => {
            return state.protectMinutes
        }
    }
}